package org.zjx.battle;

import org.zjx.battle.entity.Battle;
import org.zjx.battle.entity.Enemy;
import org.zjx.common.model.RouteProperties;
import org.zjx.team.ITeam;
import org.zjx.team.TeamManager;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class BattleManager {
    private static final Map<String, Battle> battleMap = new ConcurrentHashMap<>();

    private static final class InstanceHolder {
        static final BattleManager instance = new BattleManager();
    }

    public static BattleManager getInstance() {
        return InstanceHolder.instance;
    }

    public synchronized Battle updateBattleEnemies(String playerId, List<Enemy> enemies) {
        Battle battle = getBattleByPlayerId(playerId);
        if (battle == null) return null;
        battle.setEnemies(enemies);
        return battle;
    }

    public synchronized Battle updateBattleBloods(String playerId, List<Integer> bloods) {
        Battle battle = getBattleByPlayerId(playerId);
        if (battle == null) return null;
        battle.setBloods(bloods);
        return battle;
    }

    public synchronized Battle updateBattleRouteProperties(RouteProperties routeProperties) {
        Battle battle = getBattleByPlayerId(routeProperties.getPlayerId());
        if (battle == null) return null;
        battle.upData(routeProperties);
        return battle;
    }

    public synchronized RouteProperties getRouteProperties(String playerId) {
        Battle battle = getBattleByPlayerId(playerId);
        if (battle == null) return null;
        return battle.getRoutePropertiesMap().getOrDefault(playerId, null);
    }

    public synchronized Battle getBattleByPlayerId(String playerId) {
        ITeam team = TeamManager.getInstance().getTeamByPlayer(playerId);
        if (team == null) return null;
        Battle battle = battleMap.get(team.getTeamId());
        if (battle == null) {
            battle = new Battle(team, new ArrayList<>());
            battleMap.put(team.getTeamId(), battle);
        }
        return battle;
    }
}
